import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:wms/utils/utils.dart';
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart'; 
import 'package:flutter/services.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';

class CheckinScreen extends StatefulWidget {
  const CheckinScreen({super.key});

  @override
  _CheckinScreenScreenState createState() => _CheckinScreenScreenState();
}

class _CheckinScreenScreenState extends State<CheckinScreen> with WidgetsBindingObserver {
  final _barcodeController = TextEditingController();
  bool _isButtonEnabled = false;
  bool _isLoading = false;
  bool _isReadOnly = false;
  final FocusNode _barcodeFocusNode = FocusNode();
  int? warehouseId;
  bool _isKeyboardVisible = false;
  late double _fontScale;
  // 新增：标记是否是首次进入

  @override
  void initState() {
    super.initState();
    // 监听应用生命周期
    _isKeyboardVisible = false;
    WidgetsBinding.instance.addObserver(this);
    _barcodeController.addListener(_updateButtonState);
    _barcodeFocusNode.addListener(_handleFocusChange);
    
    // 初始状态处理
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _resetKeyboardState();
      }
    });
  }

  @override
  void dispose() {
    // 移除生命周期监听
    WidgetsBinding.instance.removeObserver(this);
    _barcodeController.removeListener(_updateButtonState);
    _barcodeController.dispose();
    _barcodeFocusNode.removeListener(_handleFocusChange);
    _barcodeFocusNode.dispose();
    super.dispose();
  }

  // 监听页面重新进入前台
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      // 当页面从后台回到前台时，强制隐藏键盘
      _resetKeyboardState();
    }
  }

  // 重置键盘状态（核心修复）
  void _resetKeyboardState() {
    // 强制重置状态
    setState(() {
      _isKeyboardVisible = false;
    });
    // 先清除焦点再重新设置，打破系统状态记忆
    _barcodeFocusNode.unfocus();
    Future.delayed(const Duration(milliseconds: 50), () {
      if (mounted) {
        _barcodeFocusNode.requestFocus();
        // 双重保险：连续两次隐藏键盘，确保覆盖系统状态
        _hideKeyboard();
        Future.delayed(const Duration(milliseconds: 100), () {
          if (mounted) _hideKeyboard();
        });
      }
    });
  }

  // 封装键盘控制方法
  void _showKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
      print('键盘已显示');
    } catch (e) {
      print('显示键盘失败: $e');
    }
  }

  void _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      print('键盘已隐藏');
    } catch (e) {
      print('隐藏键盘失败: $e');
    }
  }

  // 处理焦点变化
  void _handleFocusChange() {
    if (_barcodeFocusNode.hasFocus && !_isKeyboardVisible) {
      _hideKeyboard();
    }
  }

  // 切换键盘显示状态
  void _toggleKeyboardVisibility() {
    setState(() {
      _isKeyboardVisible = !_isKeyboardVisible;
    });

    FocusScope.of(context).requestFocus(_barcodeFocusNode);
    
    Future.delayed(const Duration(milliseconds: 150), () {
      if (_isKeyboardVisible) {
        _showKeyboard();
      } else {
        _hideKeyboard();
      }
    });
  }

  void _updateButtonState() {
    final hasText = _barcodeController.text.trim().isNotEmpty;
    if (_isButtonEnabled != hasText) {
      setState(() {
        _isButtonEnabled = hasText;
      });
    }
  }

  // 处理扫描枪输入
  void _handleScanBarcode(String value) {
    String parsedValue = value;
    try {
      if(value.contains(':')){
        parsedValue = Utils.parseQRCode(value, 'order number');
      }
    } catch (e) {
      print("JSON解析失败: $e");
    }
    print('parsedValue--$parsedValue');
    
    if (mounted) {
      setState(() {
        _barcodeController.text = parsedValue;
        _barcodeController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: parsedValue.length,
        );
      });
    }
    
    _handleSubmitted();
  }

  // 调用API获取详情数据
  Future<Map<String, dynamic>> _fetchCheckinDetails(String barcode) async {
    final warehouseIdParam = '&warehouse=$warehouseId';
    final apiUrl = '${ApiService.baseURL}${ApiService.fetchCheckin}$barcode$warehouseIdParam';

    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw 'The session has expired, Please log in again.';
    }
    
    try {
      print('apiUrl1111-----$apiUrl');
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'X-Client-Type':'app'
        },
      ).timeout(const Duration(seconds: 10));
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsondate:$jsonData');
        if (jsonData['code'] == 2000 && jsonData['data'] != null && jsonData['data'] != '') {
          return jsonData;
        }
        else if (jsonData['code'] == 401) {
          AuthService auth = AuthService();
          auth.logout(context);
          throw 'The session has expired, Please log in again.';
        }
        else {
          throw jsonData['msg'];
        }
      }
      else {
        throw response.statusCode;
      }
    } catch (e) {
      throw e;
    }
  }
  
  // 提交处理
  void _handleSubmitted() async {
    if (!_isButtonEnabled || _isLoading) return;
    
    setState(() {
      _isKeyboardVisible = false;
    });
    _hideKeyboard();
    
    if (mounted) {
      setState(() {
        _isLoading = true;
        _isReadOnly = true;
      });
    }
    
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(child: CircularProgressIndicator()),
    );

    try {
      final details = await _fetchCheckinDetails(_barcodeController.text.trim());
      
      if (!mounted) return;

      Navigator.pop(context);
      Navigator.pushNamed(
        context,
        '/inbound/checkin-detail',
        arguments: details,
      );
    } catch (e) {
      if (mounted) {
        Navigator.pop(context);
        MessageBox.showMessageBox(context,e,isError:true);
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
          _isReadOnly = false;
        });
        _resetKeyboardState(); // 提交后重置键盘状态
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    return Scaffold(
      appBar: AppBar(
        title: Text('Checkin',style: TextStyle(fontSize: 18 * _fontScale),),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pushNamed(context, '/inbound'),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363)
      ),
      body: GestureDetector(
        // 点击空白区域时取消所有输入框焦点
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        // 确保空白区域也能响应点击事件
        behavior: HitTestBehavior.opaque,
        child:Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            children: [
              const SizedBox(height: 16),
              Row(
                children: [
                  Expanded(
                    child: TextField(
                      readOnly: _isReadOnly,
                      controller: _barcodeController,
                      focusNode: _barcodeFocusNode,
                      autofocus: false,
                      keyboardType:TextInputType.text,
                      decoration: InputDecoration(
                        labelText: 'Or Enter Barcode Manually',
                        border: const OutlineInputBorder(borderRadius: BorderRadius.all(Radius.zero)),
                        prefixIcon: const Icon(Icons.qr_code),
                        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                        suffixIcon: IconButton(
                          icon: Icon(
                            _isKeyboardVisible ? Icons.keyboard_hide : Icons.keyboard,
                            color: const Color(0xFF008363),
                          ),
                          onPressed: _toggleKeyboardVisibility,
                          splashRadius: 24,
                          padding: const EdgeInsets.all(8),
                          constraints: const BoxConstraints.tightFor(width: 48, height: 48),
                        ),
                        hintText: _isKeyboardVisible 
                            ? 'Type barcode here...' 
                            : 'Ready to scan (tap keyboard icon to type)',
                      ),
                      onChanged: (value) => _updateButtonState(),
                      onSubmitted: _handleScanBarcode,
                      onTap: () {
                        if (_barcodeController.text.isNotEmpty) {
                          _barcodeController.selection = TextSelection(
                            baseOffset: 0,
                            extentOffset: _barcodeController.text.length,
                          );
                        }
                      },
                    ),
                  ),
                  SizedBox(
                    width: 60,
                    height: 48,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _isButtonEnabled ? const Color(0xFF008363) : Colors.grey,
                        shape: const RoundedRectangleBorder(
                          borderRadius: BorderRadius.zero,
                        ),
                        padding: EdgeInsets.zero,
                      ),
                      onPressed: _isButtonEnabled && !_isLoading
                          ? _handleSubmitted
                          : null,
                      child: _isLoading 
                        ? const SizedBox(
                            width: 20,
                            height: 20,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              color: Colors.white,
                            ),
                          ) 
                        : const Text('GO', style: TextStyle(fontSize: 15, color: Colors.white)),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      )
    );
  }
}